package edu.msg.hrappy.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.msg.hrappy.backend.model.Candidate;
import edu.msg.hrappy.backend.model.User;
import edu.msg.hrappy.backend.service.CandidateService;
import edu.msg.hrappy.backend.service.UserService;


public class InterviewersServlet extends HttpServlet {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@EJB
    private CandidateService candidateService;
    @EJB
    private UserService userService;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        HttpSession session = req.getSession();
        
        session.setAttribute("er", null);

        Long id = Long.parseLong(req.getParameter("candidateId"));
        
        Candidate candidate = candidateService.getById(id);
        
        List<User> users = userService.getAll();
        List<User> involved = candidate.getInterviewers();
        users.removeAll(involved);
        session.setAttribute("candidate", candidate);
        session.setAttribute("users", users);
        session.setAttribute("involved", involved);
        String address = "./interviewers.jsp";

        RequestDispatcher dispatcher = req.getRequestDispatcher(address);

        dispatcher.forward(req, resp);

    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        HttpSession session = req.getSession();
        session.setAttribute("er", null);

        Long id = Long.parseLong(req.getParameter("candidateId"));
        Long userId = Long.parseLong(req.getParameter("userId"));
        Candidate candidate = candidateService.getById(id);
        User user = userService.getById(userId);
        String add = req.getParameter("add");
        String remove = req.getParameter("remove");
        if (add!=null){
        	candidate.addInterviewer(user);
        }else if (remove!=null){
        	candidate.removeInterviewer(user);
        }
        candidateService.update(candidate);
        List<User> users = userService.getAll();
        List<User> involved = candidate.getInterviewers();
        users.removeAll(involved);
        session.setAttribute("candidate", candidate);
        session.setAttribute("users", users);
        session.setAttribute("involved", involved);
        String address = "./interviewers.jsp";

        RequestDispatcher dispatcher = req.getRequestDispatcher(address);

        dispatcher.forward(req, resp);

    }
}
